package com.cduestc.mylogin;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VerifyTheWay extends AppCompatActivity {

    TextView tvMode,tvLogo;
    ListView lvMode;
    Button btnNow;
    String emailVerificationCode;
    String phoneVerificationCode;
    SharedPreferences shareV;
    int state = 60;
    int state2 = 60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify);

        tvMode = this.findViewById(R.id.tvMode);
        lvMode = this.findViewById(R.id.lvMode);
        btnNow = this.findViewById(R.id.btnNow);
        tvLogo = this.findViewById(R.id.tvLogo);
        shareV = this.getSharedPreferences("selfMsg",MODE_PRIVATE);

        String ema1 = shareV.getString("email","");
        String pho1 = shareV.getString("phone","");
        String bir1 = shareV.getString("birth","");

        String[] modes = {"邮箱验证","短信验证","密保问题"};
        int[] img = {
                android.R.drawable.ic_dialog_email,
                android.R.drawable.ic_menu_call,
                android.R.drawable.ic_lock_lock
        };
        String[] logo = {"已绑定","已绑定","已绑定"};

        if(ema1.equals("")){
            logo[0] = "未绑定";
        }
        if(pho1.equals("")){
            logo[1] = "未绑定";
        }

        List lst = new ArrayList();
        for(int x = 0 ; x < modes.length ; x++){
            Map map = new HashMap();
            map.put("mode1",img[x]);
            map.put("mode2",modes[x]);
            map.put("mode3",logo[x]);
            lst.add(map);
        }

        SimpleAdapter spAdapter = new SimpleAdapter(
                VerifyTheWay.this,
                lst,
                R.layout.adapter,
                new String[]{"mode1","mode2","mode3"},
                new int[]{R.id.img,R.id.tvMo,R.id.tvLo}
        );
        lvMode.setAdapter(spAdapter);

        lvMode.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                TextView tvMo = view.findViewById(R.id.tvMo);
                TextView tvLo = view.findViewById(R.id.tvLo);
                String mode = tvMo.getText().toString().trim();
                String logo = "(" + tvLo.getText().toString().trim() + ")";
                tvMode.setText(mode);
                tvLogo.setText(logo);
            }
        });

        btnNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (tvMode.getText().toString()){
                    case "邮箱验证":{
                        if(logo[0] == "未绑定"){
                            Toast.makeText(VerifyTheWay.this, "邮箱未绑定，请选择其它验证方式", Toast.LENGTH_SHORT).show();
                            return;
                        }else{
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(VerifyTheWay.this);
                            View viewE = View.inflate(VerifyTheWay.this, R.layout.evalidation, null);
                            EditText vEmail,etVal;
                            Button btnSentVal;

                            vEmail = viewE.findViewById(R.id.vEmail);
                            etVal = viewE.findViewById(R.id.etVal);
                            btnSentVal = viewE.findViewById(R.id.btnSentVal);
                            ProgressBar eBar = viewE.findViewById(R.id.eBar);

                            builder1.setIcon(android.R.drawable.ic_dialog_email)
                                    .setTitle("邮箱验证")
                                    .setView(viewE)
                                    .setPositiveButton("验证",null);

                            final AlertDialog dialog = builder1.create();
                            dialog.show();

                            Handler hand2 = new Handler(){
                                @Override
                                public void handleMessage(Message msg){
                                    super.handleMessage(msg);
                                    if(msg.what == 0x111){
                                        eBar.setProgress(state2);
                                    }
                                }
                            };
                            CountDownTimer cdt1 = new CountDownTimer(60*1000,1000)
                            {
                                boolean flag;
                                @Override
                                public void onTick(long l) {
                                    flag = true;
                                    btnSentVal.setClickable(false);
                                    btnSentVal.setBackgroundColor(Color.parseColor("#ff0000"));
                                    btnSentVal.setText((l / 1000) + "秒后重新发送");
                                }
                                @Override
                                public void onFinish() {
                                    flag = false;
                                    btnSentVal.setClickable(true);
                                    btnSentVal.setBackgroundColor(Color.parseColor("#0000ff"));
                                    String wrongRes = String.valueOf((Math.random()*9+1)*100000);
                                    while(true){
                                        if(wrongRes != emailVerificationCode){
                                            emailVerificationCode = wrongRes;
                                            break;
                                        }
                                    }
                                    Toast.makeText(VerifyTheWay.this, "验证码已失效，请点击重新获取", Toast.LENGTH_SHORT).show();
                                    btnSentVal.setText("重新发送");
                                }
                            };
                            btnSentVal.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) throws IllegalThreadStateException{
                                    String eml = vEmail.getText().toString().trim();
                                    if(eml.equals("")){
                                        Toast.makeText(VerifyTheWay.this, "请输入您绑定的邮箱", Toast.LENGTH_SHORT).show();
                                        return;
                                    }else if(!eml.equals(ema1)){
                                        Toast.makeText(VerifyTheWay.this, "与绑定的邮箱不一致，请重新输入", Toast.LENGTH_SHORT).show();
                                        return;
                                    }else {
                                        state2 = 60;
                                        new Thread(){
                                            public void run(){
                                                while(state2 >= 0){
                                                    state2 = countDown2();
                                                    Message mg = new Message();
                                                    mg.what = 0x111;
                                                    hand2.sendMessage(mg);
                                                }
                                            }
                                        }.start();
                                        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                                        cdt1.start();
                                        int r = (int)((Math.random()*9+1)*100000);
                                        String rs = String.valueOf(r);
                                        emailVerificationCode = rs;
                                        Notification.Builder builder = new Notification.Builder(VerifyTheWay.this);
                                        builder.setSmallIcon(android.R.drawable.ic_dialog_email);
                                        builder.setContentTitle("收件人：" + eml);
                                        builder.setContentText("验证码:" + rs);
                                        builder.setDefaults(Notification.DEFAULT_ALL);
                                        builder.setAutoCancel(true);
                                        Notification notifi = builder.build();
                                        Toast.makeText(VerifyTheWay.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                                        notificationManager.notify(1, notifi);
                                    }
                                }
                                public int countDown2(){
                                    state2--;
                                    try{
                                        Thread.sleep(1000);
                                    }catch (InterruptedException e){
                                        e.printStackTrace();
                                    }
                                    return state2;
                                }
                            });

                            dialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String etv = etVal.getText().toString().trim();
                                    if(etv.equals("")){
                                        Toast.makeText(VerifyTheWay.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                                    }else if(!etv.equals(emailVerificationCode)){
                                        Toast.makeText(VerifyTheWay.this, "验证码错误或已失效", Toast.LENGTH_SHORT).show();
                                        etVal.setText("");
                                    }else{
                                        Toast.makeText(VerifyTheWay.this, "验证通过", Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(VerifyTheWay.this,PwdChange.class);
                                        startActivity(intent);
                                    }
                                }
                            });
                        }
                    }
                    break;
                    case "短信验证":{
                        if(logo[1] == "未绑定"){
                            Toast.makeText(VerifyTheWay.this, "手机号未绑定，请选择其它验证方式", Toast.LENGTH_SHORT).show();
                        }else{
                            EditText vPhone,ptVal;
                            Button btnSentValPhone;

                            AlertDialog.Builder builder2 = new AlertDialog.Builder(VerifyTheWay.this);
                            View viewP = View.inflate(VerifyTheWay.this, R.layout.pvalidation, null);

                            vPhone = viewP.findViewById(R.id.vPhone);
                            ptVal = viewP.findViewById(R.id.ptVal);
                            ProgressBar pBar = viewP.findViewById(R.id.pBar);

                            Handler hand = new Handler(){
                                @Override
                                public void handleMessage(Message msg){
                                    super.handleMessage(msg);
                                    if(msg.what == 0x111){
                                        pBar.setProgress(state);
                                    }
                                }
                            };

                            btnSentValPhone = viewP.findViewById(R.id.btnSentValPhone);

                            builder2.setIcon(android.R.drawable.ic_menu_call)
                                    .setTitle("短信验证")
                                    .setView(viewP)
                                    .setPositiveButton("验证",null);
                            final AlertDialog dialog2 = builder2.create();
                            dialog2.show();

                            CountDownTimer cdt = new CountDownTimer(60*1000,1000)
                            {
                                boolean flag;
                                @Override
                                public void onTick(long l) {
                                    flag = true;
                                    btnSentValPhone.setClickable(false);
                                    btnSentValPhone.setBackgroundColor(Color.parseColor("#ff0000"));
                                    btnSentValPhone.setText((l / 1000) + "秒后重新发送");
                                }


                                @Override
                                public void onFinish() {
                                    flag = false;
                                    btnSentValPhone.setClickable(true);
                                    btnSentValPhone.setBackgroundColor(Color.parseColor("#0000ff"));
                                    String wrongRes1 = String.valueOf((Math.random()*9+1)*100000);
                                    while(true){
                                        if(wrongRes1 != phoneVerificationCode){
                                            phoneVerificationCode = wrongRes1;
                                            break;
                                        }
                                    }
                                    Toast.makeText(VerifyTheWay.this, "验证码已失效，请点击重新获取", Toast.LENGTH_SHORT).show();
                                    btnSentValPhone.setText("重新发送");
                                }
                            };

                            btnSentValPhone.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String vp = vPhone.getText().toString().trim();
                                    if(vp.equals("")){
                                        Toast.makeText(VerifyTheWay.this, "请输入您绑定的手机号", Toast.LENGTH_SHORT).show();
                                    }else if(!vp.equals(pho1)){
                                        Toast.makeText(VerifyTheWay.this, "手机号输入错误，请重新输入", Toast.LENGTH_SHORT).show();
                                        vPhone.setText("");
                                    }else{
                                        state = 60;
                                        new Thread(){
                                            public void run(){
                                                while(state >= 0){
                                                    state = countDown();
                                                    Message mg = new Message();
                                                    mg.what = 0x111;
                                                    hand.sendMessage(mg);
                                                }
                                            }
                                        }.start();
                                        int randCode = (int)((Math.random()*9+1)*100000);
                                        cdt.start();
                                        String strRandCode = String.valueOf(randCode);
                                        phoneVerificationCode = strRandCode;
                                        String content = "【登录】 验证码" + strRandCode + "（有效时间：1分钟）请勿将验证码告诉他人，如非本人操作请忽略。";
                                        SmsManager smsManager = SmsManager.getDefault();
                                        smsManager.sendTextMessage("5554", null, content,null,null);
                                        Toast.makeText(VerifyTheWay.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                                    }
                                }
                                public int countDown(){
                                    state--;
                                    try{
                                        Thread.sleep(1000);
                                    }catch (InterruptedException e){
                                        e.printStackTrace();
                                    }
                                    return state;
                                }
                            });

                            dialog2.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String ptv = ptVal.getText().toString().trim();
                                    if(ptv.equals("")){
                                        Toast.makeText(VerifyTheWay.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                                    }else if(!ptv.equals(phoneVerificationCode)){
                                        Toast.makeText(VerifyTheWay.this, "验证码错误或已失效", Toast.LENGTH_SHORT).show();
                                    }else{
                                        Toast.makeText(VerifyTheWay.this, "验证成功", Toast.LENGTH_SHORT).show();
                                        Intent intent1 = new Intent(VerifyTheWay.this,PwdChange.class);
                                        startActivity(intent1);
                                    }
                                }
                            });
                        }
                    }
                    break;
                    case "密保问题":{
                        EditText qtVal;
                        AlertDialog.Builder builder3 = new AlertDialog.Builder(VerifyTheWay.this);
                        View viewQ = View.inflate(VerifyTheWay.this, R.layout.qvalidation,null);
                        qtVal = viewQ.findViewById(R.id.qtVal);
                        builder3.setIcon(android.R.drawable.ic_lock_lock)
                                .setTitle("密保问题")
                                .setView(viewQ)
                                .setPositiveButton("验证",null);;

                        final AlertDialog dialog3 = builder3.create();
                        dialog3.show();

                        dialog3.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                String answer = qtVal.getText().toString().trim();
                                if(answer.equals("")){
                                    Toast.makeText(VerifyTheWay.this, "请输入答案", Toast.LENGTH_SHORT).show();
                                    return;
                                }else if(!answer.equals(bir1)){
                                    Toast.makeText(VerifyTheWay.this, "答案输入错误,请重新输入", Toast.LENGTH_SHORT).show();
                                    qtVal.setText("");
                                    return;
                                }else{
                                    Toast.makeText(VerifyTheWay.this, "验证成功", Toast.LENGTH_SHORT).show();
                                    Intent intent1 = new Intent(VerifyTheWay.this,PwdChange.class);
                                    startActivity(intent1);
                                }
                            }
                        });
                    }
                    break;
                    default:
                        Toast.makeText(VerifyTheWay.this, "请选择一种验证方式", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}